package com.myapp.mobilesafe.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.myapp.mobilesafe.utils.InStreamUtils;
import com.myapp.mobilesafe.utils.PrefUtils;
import com.myapp.mobilesafe.utils.SuperAdmin;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class IndexActivity extends AppCompatActivity {
    private static final int INFO_UPDATE = 1;
    private static final int INFO_TOMAIN=2;
    private static final int INFO_NETERROR=3;
    private static final int INFO_DATAERROR=4;
    private  String mVersonName;
    private int mVersonCode ;
    private String mDes;
    private RelativeLayout rlroot;
    private TextView tv_progress;
    private String mUrl ;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case INFO_UPDATE:
                    showUpdateDialog();
                    break;
                case INFO_TOMAIN:
                    toHome();
                    break;
                case INFO_NETERROR:
                    Toast.makeText(IndexActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                    toHome();
                    break;
                case INFO_DATAERROR:
                    Toast.makeText(IndexActivity.this,"数据异常",Toast.LENGTH_SHORT).show();
                    toHome();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        TextView tv = (TextView) findViewById(R.id.tv_verson);
        tv.setText("版本号："+getVersionName());
        rlroot = (RelativeLayout) findViewById(R.id.rl_root);
        tv_progress = (TextView) findViewById(R.id.tv_download);
        if(PrefUtils.getBoolean("auto_update", true,getApplicationContext())){
            checkVerson();
        }else {
            mHandler.sendEmptyMessageDelayed(INFO_TOMAIN,2000);
        }

        AlphaAnimation ala = new AlphaAnimation(0.2f,1);
        ala.setDuration(2000);
        rlroot.setAnimation(ala);
        copyDB("address.db");
        copyDB("commonnum.db");
        copyDB("antivirus.db");
        installShortcut();
    }

    /**
     * 跳转主界面
     */
    private void toHome(){
        Intent intent =  new Intent(this,HomeActivity.class);
        startActivity(intent);
        finish();
    }
    /**
     * 请求网络 检查版本是否一致
     */
    private void checkVerson(){
        Thread t = new Thread(){
            @Override
            public void run() {
                Message msg = Message.obtain();
                HttpURLConnection conn = null;
                long startTime = System.currentTimeMillis();
                String path = "http://192.168.0.109:8080/update.json";
                try {
                    URL url = new URL(path);
                     conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(3000);
                    conn.setReadTimeout(3000);
                    if(conn.getResponseCode()==200){
                        InputStream is = conn.getInputStream();
                        String result = InStreamUtils.Stream2String(is);
                        Log.i("hahah","$$"+result);
                        JSONObject json = new JSONObject(result);
                        mVersonName = json.getString("versionName");
                        mVersonCode = json.getInt("versionCode");
                         mDes = json.getString("des");
                         mUrl = json.getString("url");
                        Log.i("hahah","$$&&&&&"+mVersonCode+getVersonCode());
                        if(mVersonCode>getVersonCode()){
                            msg.what = INFO_UPDATE;
                        }else {
                            msg.what = INFO_TOMAIN;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    msg.what=INFO_NETERROR;
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.what=INFO_DATAERROR;
                } finally {
                    if(conn!=null){
                        conn.disconnect();
                    }
                    long endTime = System.currentTimeMillis();
                    try {
                        if((endTime-startTime)<3000){
                            Thread.sleep(3000 - (endTime-startTime));
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendMessage(msg);
                }

            }
        };
        t.start();
    }

    /**
     * 版本更新对话框
     */
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("发现新版本：" + mVersonName);
        builder.setMessage(mDes);
        builder.setPositiveButton("马上升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                downLoadApk();
            }
        });
        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toHome();
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                toHome();
            }
        });
        builder.show();
    }

    /**
     * 文件下载
     */
    private void downLoadApk(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mobilesafe.apk";
            tv_progress.setVisibility(View.VISIBLE);
            HttpUtils utils = new HttpUtils();
            utils.download(mUrl, path, new RequestCallBack<File>() {
                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    super.onLoading(total, current, isUploading);
                    int percent = (int) (100 * current/total);
                    tv_progress.setText("下载进度："+percent+"%");
                }

                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    String p = responseInfo.result.getAbsolutePath();
                    Log.i("hahah","###$#$#"+p);
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                    intent.setDataAndType(Uri.fromFile(responseInfo.result),
                            "application/vnd.android.package-archive");
                    startActivityForResult(intent, 0);
                }

                @Override
                public void onFailure(HttpException e, String s) {

                }
            });
        }

    }
    /**
     * 获取版本名称
     */
    private String getVersionName() {
        PackageManager pm = getPackageManager();// 包管理器
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);// 根据包名,获取相关信息
            String versionName = packageInfo.versionName;// 版本名称
            // int versionCode = packageInfo.versionCode;// 版本号
            // System.out.println("versionName:" + versionName);
            // System.out.println("versionCode:" + versionCode);
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // 包名未找到异常
            e.printStackTrace();
        }

        return "";
    }
    private int getVersonCode(){
        PackageManager pm = getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);// 根据包名,获取相关信息
            int versionCode = packageInfo.versionCode;// 版本号
            Log.i("hahah","&&&&&&&&"+versionCode);
            return versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // 包名未找到异常
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        toHome();
    }
    private void copyDB(String dbName){
        File filesDir = getFilesDir();
        File targetFile = new File(filesDir, dbName);

        // 先判断文件是否存在,如果存在,无需拷贝
        if (targetFile.exists()) {
            System.out.println("数据库" + dbName + "已经存在,无需拷贝!");
            return;
        }

        InputStream in = null;
        FileOutputStream out = null;
        try {
            AssetManager assets = getAssets();
            in = assets.open(dbName);

            out = new FileOutputStream(targetFile);

            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println("拷贝数据库" + dbName + "成功!");
    }
/**
 * 创建快捷方式
 */
private void installShortcut() {
    boolean isCreated = PrefUtils.getBoolean("is_shortcut_created", false,
            this);

    if (!isCreated) {
        Intent intent = new Intent();
        intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "安全卫士");// 快解方式名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory
                .decodeResource(getResources(), R.drawable.home_icom));// 快解方式图标

        // 跳到主页面
        Intent actionIntent = new Intent();
        actionIntent.setAction("com.myapp.mobilesafe.HOME");
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, actionIntent);

        sendBroadcast(intent);

        PrefUtils.putBoolean("is_shortcut_created", true, this);
    }

}
}
